#!/usr/bin/env python3
#-*- encoding:utf8 -*-

from flask import Flask, request
from myDatabase import db_session
from myModels import myArticle
from dateutil.parser import parse
from sqlalchemy import or_

app = Flask(__name__)

def query_data(start_time=None, end_time=None, channel=None, category=None, source=None, keyword=None, **kw):
    q = db_session.query(myArticle)
    if start_time:  # 开始时间
        q = q.filter(myArticle.ptime>=start_time[0])
    if end_time:  # 结束时间
        q = q.filter(myArticle.ptime<=end_time[0])
    if channel:  # 频道
        channel = channel[0].split(",")
        q = q.filter(or_(myArticle.channel==ch for ch in channel))
    if category:  # 类别
        category = category[0].split(",")
        q = q.filter(or_(myArticle.category==ca for ca in category))
    if source:  # 来源
        source = source[0].split(",")
        q = q.filter(or_(myArticle.source==so for so in source))
    if keyword:  # 关键词
        #keyword = keyword[0].split(",,")
        keyword = "%" + keyword[0] + "%"
        q = q.filter(or_(myArticle.digest.like(keyword), myArticle.title.like(keyword)))
    return q.all()

def to_html(metadata):
    web = """
"""
    for article in metadata:
        web += '''<strong><a href="''' + article.link + '''">''' + article.title + '''</a></strong><br>
            <div style="color:#778899">时间: ''' + article.ptime.strftime("%Y-%m-%d %H:%M:%S") + '''  来源: ''' + article.source + '''  类型: ''' \
            + article.category + '''  频道: ''' + article.channel + '''</div><br>
            <a>''' + article.digest + '''</a><br><hr />'''
    return web

@app.route("/query", methods=["GET"])
def index():
    query_stream = dict(request.args)
    print(query_stream)
    result = query_data(**query_stream)
    return to_html(result)




    return "Welcome!"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=18080)

